module Gadgets
  class Combobox < Gtk::HBox
    def initialize(data, type)
      super()
      
      @model = Gtk::ListStore.new(*type)
      data.each do |t|
        iter = @model.append
        iter[0] = t[0]
        iter[1] = t[1]
      end
      
      @combobox = Gtk::ComboBox.new(@model)
      renderer = Gtk::CellRendererText.new
      @combobox.pack_start(renderer, true)
      @combobox.set_attributes(renderer, :text => 0)
      @combobox.active = 0
      self.add(@combobox)
    end
    
    def selected_iter
      return @model.get_iter(Gtk::TreePath.new(self.active))
    end
    
    def selected_text
      self.selected_iter[0]
    end
    
    def selected_data
      self.selected_iter[1]
    end
    
    def value
      self.selected_iter[1]
    end
    
    def value=(value)
      self.select(value)
    end
    
    def active=(index)
      return @combobox.active = index
    end
    
    def active
      return @combobox.active
    end
    
    def signal_connect(type, &func)
      @combobox.signal_connect(type) {|*args| func.call(*args)}
    end
    
    def select(value)
      iter = @model.iter_first
      return unless iter

      begin
        break if iter[1] == value
      end while iter.next!
      
      if iter
        @combobox.set_active_iter(iter)
      else
        @combobox.active = 0
      end
    end
  end
end